//
//  MaterialAcceptResultsAddController.m
//  ERP
//
//  Created by QA on 2016/10/21.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MaterialAcceptResultsAddController.h"
#import "GETableView.h"

#import "GEInputTableViewCell.h"
#import "FileUploadModel.h"
#import "UploadViewController.h"
#import "PreviewLocalFileHelper.h"
#import "GEObjectButton.h"
#import "FileSizeFormatHelper.h"
#import "FileTypeIcon.h"
#import "NSKeyedArchiverUserLogin.h"
#import "GEPickerTextField.h"
#import "NSDictionary+DataFormat.h"
#import "MaterialAcceptCreateCell.h"

//#import "SiteInspectionContractViewController.h"
//#import "SiteInspectionProjectViewController.h"
#import "MaterialAcceptCreateController.h"

#import "AutoTextTableViewCell.h"
#import "MaterialAcceptNextCell.h"
#import "DownFileInfoCell.h"

#import "DownLoadHandle.h"
#import "PreviewFileHelper.h"

@interface MaterialAcceptResultsAddController()

@property (nonatomic,strong) IBOutlet GETableView *tableView;
@property (nonatomic, strong) NSMutableArray *accessoryArray;
@property (nonatomic, strong) NSDictionary *invoiceData;

@property (strong, nonatomic) NSMutableArray *resultData;
@property (nonatomic, assign) NSInteger downFileState;//0加载中，1未找到数据，2加载失败，3加载成功

@end

@implementation MaterialAcceptResultsAddController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"材料验收补充"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.accessoryArray = [NSMutableArray array];
    self.resultData = [NSMutableArray array];
    
    NSDictionary *mDictionary = self.value;
    self.invoiceData = mDictionary;
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    
    //获取扣重项目
    [self getNetWorkDataYCID:mDictionary];
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getPassingParameter:(id)object
{
    //提前加载预绘制项目
    NSInteger section = [self numberOfSectionsInTableView:_tableView];
    for (int i=0; i<section; i++) {
        NSInteger row = [self tableView:_tableView numberOfRowsInSection:i];
        for(int j=0; j<row; j++){
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
            [self tableView:_tableView cellForRowAtIndexPath:indexPath];
        }
    }
}

#pragma mark 网络获取数据

- (void)getNetWorkDataYCID:(NSDictionary*)mDictionary
{
    NSString *Id = [mDictionary objectFormatStringForKey:@"Id"];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"YCYS_GET_INFO"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"ID" value:Id];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = result.resultArray;
        [self.resultData removeAllObjects];
        
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            self.downFileState = 3;
            
            //处理无数据情况
            if(self.resultData.count >= 2){
                NSArray *arrayImg = [self.resultData objectAtIndex:1];
                if(arrayImg.count<=0) self.downFileState = 1;
            }
        } else {
            self.downFileState = 1;
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.downFileState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.downFileState = 2;
        [self.tableView reloadData];
    }];
    
}

#pragma mark UIButton Event

//通过验收
- (void)passSelector:(UIButton *)button
{
    [self submitTheLogGenerateHandle];
}

- (void)submitTheLogGenerateHandle
{
    //获取用户信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    
    //处理照片信息
    NSMutableString *imageURLs = [NSMutableString string];
    for(FileUploadModel *model in self.accessoryArray){
        NSDictionary *jsonDictionary = [model getFileInfo];
        NSString *filePath = [jsonDictionary objectFormatForKey:@"filePath"];
        [imageURLs appendFormat:@"%@,",filePath];
    }
    if(imageURLs.length > 0)
        [imageURLs deleteCharactersInRange:NSMakeRange(imageURLs.length - 1, 1)];
    
    NSString *ID = [self.invoiceData objectFormatIntStringForKey:@"Id"];
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setShowLoadingPrompt:self.navigationController labelText:@"正在提交"];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"YCYS_IMG_MAKEUP"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    [content addParameterKey:@"ID" value:ID];
    [content addParameterKey:@"图片地址" value:imageURLs];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:@"补充成功"];
            if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:nil dataValue:nil];
            
            // 延迟2.2秒执行：
            double delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            });
            
        } else{
            [self showErrorHUDText:@"补充失败"];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"补充失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"补充失败"];
    }];
    
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0 && self.resultData.count >= 2) {
        NSArray *array = [self.resultData objectAtIndex:1];
        return array.count > 0 ? array.count : 1;
    }
    
    if(section == 1) {
        return self.accessoryArray.count + 1;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"CreateContractViewController%ld%ld",indexPath.section,indexPath.row];
    GEInputTableViewCell *cell = [self.tableView getCellViewInRow:indexPath.row inSection:indexPath.section];
    if (cell != nil) return cell;
    
    //见证取样
    if(indexPath.section == 0){
        if (self.downFileState == 3) {
            DownFileInfoCell *cell = [[DownFileInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
            NSArray *arrayImg = [self.resultData objectAtIndex:1];
            NSDictionary *fileDictionary = [arrayImg objectAtIndex:indexPath.row];
            cell.fileName.text = [fileDictionary objectFormatStringForKey:@"图片名称"];
            cell.fileSize.text = [fileDictionary objectFormatStringForKey:@"图片大小" defaults:@"未知"];
            cell.iconImageView.image = [FileTypeIcon setFileTypeIcon:[fileDictionary objectFormatStringForKey:@"图片路径"]];
            
            cell.downButton.userInteractionEnabled = YES;
            cell.downButton.tag = indexPath.row;
            [cell.downButton addTarget:self action:@selector(downadjunctFile:) forControlEvents:UIControlEventTouchUpInside];
            
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
            cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 50);
            
            if(self.downFileState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 30.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.downFileState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"无取样图片";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.downFileState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"数据加载失败";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    //见证取样
    else if(indexPath.section == 1){
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.bounds = CGRectMake(0, 0, SuperWidth, 48);
        
        if (indexPath.row < self.accessoryArray.count) {
            FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
            [self drawRowFileCell:cell model:model indexPath:indexPath];
        } else {
            UIImage *image = [UIImage imageNamed:@"button_bg_add"];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.frame.size.width/2-image.size.width/2, cell.frame.size.height/2-image.size.height/2 + 3, image.size.width, image.size.height)];
            [imageView setImage:image];
            [cell.contentView addSubview:imageView];
        }
        return cell;
    }
    
    //处理按钮
    else if(indexPath.section == 2){
        MaterialAcceptCreateCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[MaterialAcceptCreateCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier index:1];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor clearColor];
            
            [cell.passButton addTarget:self action:@selector(passSelector:) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
    }
    
    return nil;
}

//添加文件
- (void)drawRowFileCell:(UITableViewCell*)cell model:(FileUploadModel *)model indexPath:(NSIndexPath *)indexPath
{
    CGSize cellSize = cell.frame.size;
    cellSize.height = 50;
    cellSize.width = SuperWidth;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, cellSize.height - 10, cellSize.height - 10)];
    imageView.image = [FileTypeIcon setFileTypeIcon:model.filePath];
    [cell.contentView addSubview:imageView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, 3, cellSize.width - cellSize.height - 60, cellSize.height/2)];
    titleLabel.text = model.fileName;
    titleLabel.font = [UIFont systemFontOfSize:15.0];
    titleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:titleLabel];
    
    NSString *fileSize = [FileSizeFormatHelper getFileSizeString:[NSString stringWithFormat:@"%lld",model.fileSize]];
    UILabel *field = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, cellSize.height/2 - 2, cellSize.width - cellSize.height - 10, cellSize.height/2)];
    field.font = [UIFont systemFontOfSize:12.0];
    field.text = [NSString stringWithFormat:@"文件大小：%@", fileSize] ;
    field.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:field];
    
    GEObjectButton *button = [GEObjectButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(cellSize.width - 70, 0, cellSize.height, cellSize.height);
    [button setImage:[UIImage imageNamed:@"del.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(delFileSelector:) forControlEvents:UIControlEventTouchUpInside];
    button.object = @[@(indexPath.section), model];
    [cell.contentView addSubview:button];
    
    //添加分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 1, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [cell.contentView addSubview:lineView];
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor clearColor];
    if(section == 2) return view;
    
    UIView *viewBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    viewBackground.backgroundColor = [UIColor whiteColor];
    [view addSubview:viewBackground];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    if(section == 0){
        lable.text = @"已有材料取样";
    } else if(section == 1){
        lable.text = @"新增材料取样";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) return 0.0001;
    else return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) return self.resultData.count>0 ? 44 : 48;
    return 54;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //预览文件
    if(indexPath.section == 0 && self.downFileState == 3) {
        if(self.resultData.count<2) return;
        NSArray *arrayImg = [self.resultData objectAtIndex:1];
        if(indexPath.row > arrayImg.count) return;
        
        NSDictionary *fileDictionary = [arrayImg objectAtIndex:indexPath.row];
        NSString *fileName = [fileDictionary objectFormatStringForKey:@"图片名称"];
        NSString *filePath = [fileDictionary objectFormatStringForKey:@"图片路径"];
        
        //ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
        //filePath = [NSString stringWithFormat:@"%@/upload/%@",model.IpAddress,filePath];
        
        //创建连接，预览文件
        PreviewFileHelper *preview = [[PreviewFileHelper alloc] init];
        [preview startPreviewExternalFile:filePath fileName:fileName];
    }
    
    //添加附件
    else if (indexPath.section == 1 && indexPath.row ==([self tableView:nil numberOfRowsInSection:1] - 1)) {
        UploadViewController *abstractView = [[UploadViewController alloc] init];
        [abstractView setNumberType:@"2" extension:@"bmp,jpg,gif,png"];
        
        abstractView.key = @"AccessoryFile";
        abstractView.backResultDelagate = self;
        [self.navigationController pushViewController:abstractView animated:YES];
    }
    
    //附件预览
    else if (indexPath.section == 1){
        FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
        PreviewLocalFileHelper *preview = [PreviewLocalFileHelper instantiation];
        [preview previewViewController:self localFile:model.filePath];
    }
    
}

#pragma mark -
#pragma mark Button Event

- (void)delFileSelector:(GEObjectButton*)button
{
    NSArray *array = button.object;
    NSInteger section = [array[0] integerValue];
    id delValue = array[1];
    
    if (section == 1 && self.accessoryArray.count>0) {
        NSInteger index = [self.accessoryArray indexOfObject:delValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
        
        NSArray *delIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.accessoryArray removeObject:delValue];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:delIndexPath withRowAnimation:UITableViewRowAnimationLeft];
        [self.tableView endUpdates];
    }
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    [super backResultDataKey:key dataValue:backValue];
    NSArray *array = backValue;
    if (!(array && array.count>0)) return;
    
    if([key isEqualToString:@"AccessoryFile"]){
        //添加附件
        if ([backValue isKindOfClass:[NSArray class]]) {
            NSMutableArray *insertIndexPath = [NSMutableArray array];
            for (int i=0;i<array.count;i++) {
                id value = [array objectAtIndex:i];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
                [insertIndexPath addObject:indexPath];
                [self.accessoryArray insertObject:value atIndex:0];
            }
            
            if (insertIndexPath.count>0) {
                [self.tableView beginUpdates];
                [self.tableView insertRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationTop];
                [self.tableView endUpdates];
            }
        }
    }
}

#pragma mark Button Event

- (void)downadjunctFile:(UIButton*)button
{
    //下载附件
    if(self.resultData.count<2) return;
    NSArray *arrayImg = [self.resultData objectAtIndex:1];
    if(button.tag > arrayImg.count) return;
    
    NSDictionary *fileDictionary = [arrayImg objectAtIndex:button.tag];
    NSString *fileName = [fileDictionary objectFormatStringForKey:@"图片名称"];
    NSString *filePath = [fileDictionary objectFormatStringForKey:@"图片路径"];
    
    //ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
    //filePath = [NSString stringWithFormat:@"%@/upload/%@",model.IpAddress,filePath];
    
    //创建连接，下载文件
    DownLoadHandle *downLoad = [[DownLoadHandle alloc] init];
    [downLoad startDownExternalFile:filePath fileName:fileName];
}

#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

@end
